var app = getApp(), fetchApi = require("../../../utils/httpPost.js"), common_Js = require("../../../component/common.js")
import Dialog from '../../../component/vant/dialog/dialog';
import Toast from '../../../component/vant/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageSize:10,
    pageIndex: 1,
    scrollTop: 0,
    scrollHeight:0,
    deviceList:[],
    hasData:false,
    loading: false,
    netWork: false,
    isLoading: true,
    visible:false,
    itemData:[],
    currentTab:0,
    tabs: ['待保养', '已保养'],
    tabs_state: [0,1],
    health:0,
    shopId:0,
    shop:{},
    shop_type:0,
    device_type:0,
    is_test:0,
    time: 31 * 1000,
    timeData: {},
    feedList:  [],
    copyFeedList:  [],
    position:1,
    feedindex:0,
    feedSwitch: false,
    searchKey: '',
    selectNode:{}
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options',options)
    this.data.health = parseInt(options.state);
    if(options.shopId){
      this.data.shopId = parseInt(options.shopId);
    }
    if(options.shop_type){
      this.data.shop_type = parseInt(options.shop_type);
      this.setData({
        shop_type:parseInt(options.shop_type)
      })
    }
    
    if(options.position){
      this.data.position = parseInt(options.position);
    }
    if(options.device_type){
      this.data.device_type = parseInt(options.device_type);
    }
    this.setData({
      scrollHeight: app.globalData.windowHeight + 4,
    })
    this.data.is_test = app.getStorageSync("is_test");
    this.setData({
      is_test: this.data.is_test
    })
    this.onHttpInit()
  },
  onChange:function(event) {
    console.log('onChange',event)
    var index = event.detail.index;
    var health = this.data.tabs_state[index];

    this.data.pageIndex = 1;
    this.setData({
      currentTab:index,
      loading: false,
      netWork: false,
      isLoading: true,
      hasData:false,
      deviceList:[]
    });
    this.data.health = health
    this.onHttpInit(health);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow:function(){
    // this.data.pageIndex = 1
    // this.setData({
    //   loading: false,
    //   netWork: false,
    //   isLoading: true,
    //   hasData:false,
    //   deviceList:[]
    // });
    // this.onHttpInit()
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this
    fetchApi.httpPost('/device/list/new', {
      device_type: that.data.device_type,
      shop_type: that.data.shop_type,
      shopId: that.data.shopId,
      pageSize:that.data.pageSize,
      pageIndex:that.data.pageIndex,
      position: that.data.position,
    }, function (res) {
      console.log("传感器设备列表数据", res)
      if (res.data.code == 0) {
        if (res.data.totalcount > 0) {
          that.data.pageIndex = that.data.pageIndex + 1;
          that.data.shop = res.data.data.shop;
          var devices = res.data.data.deviceList;
          console.log('devices',devices)
          for (var index in devices) {
            that.data.deviceList.splice(that.data.deviceList.length, 0, devices[index]);
          }
          that.data.feedList = res.data.data.feedList;
          console.log('devices',res.data.data.feedList)
          that.setData({
            hasData: true,
            shop: that.data.shop,
            deviceList: that.data.deviceList,
            feedList: that.data.feedList,
            copyFeedList:  that.data.feedList
          })
        }
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
        
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
    })
  },
  goMeasure(e){
    var deviceNum = e.currentTarget.dataset.num;
    var deviceId = e.currentTarget.dataset.id;
    var deviceType =  e.currentTarget.dataset.type;
    var item =  e.currentTarget.dataset.item;
    var index = e.currentTarget.dataset.index;

    if(item.onlineState == 0){
      Toast.fail('设备已离线，请检查后操作！');
      return;
    }


    var that = this;
    fetchApi.httpPost('/device/startMeasure', {
      device_id: deviceId,
      order: deviceType == 0 ? "04" : "06",
      sn:deviceNum,
      data:"01",
    }, function (res) {
      console.log("发起设备操作，测量响应数据", res)
      if (res.data.code == 0) {
        that.data.deviceList[index].isMeasure = 1;
        that.setData({
          deviceList:that.data.deviceList
        })
        Toast("设备正在测量,请稍后下拉刷新")
      }else{
        Toast("设备操作异常，请重试")
      }
    }, function (res) {
        Toast("设备操作异常，请重试")
       
    })
  },
  onChangeCountDown(e) {
    console.log('onChangeCountDown',e)
    var index = e.currentTarget.dataset.index;
    // this.data.deviceList[index].measureSeconds;
    this.data.deviceList[index].timeData = e.detail
    this.setData({
      deviceList: this.data.deviceList
    });
  },
  /**
   *  测量倒计时结束 重新刷新
   */
  finishedTime(e){
    var id = e.currentTarget.dataset.id;

    var index = e.currentTarget.dataset.index;
    
    this.onHttpDetail(id,index)
  },
  
  /**
   * 获取页面数据的 http请求
   */
  onHttpDetail: function (device_id,index) {
    var that = this
    fetchApi.httpPost('/device/range/detail', {
      device_id: device_id,
    }, function (res) {
      console.log("传感器设备列表数据", res)
      if (res.data.code == 0) {
        var device = res.data.data.deviceRange;
        that.data.deviceList[index] = device;        
        that.setData({
          deviceList: that.data.deviceList,
        })
      }
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
  },
  preImg: function (t) {
    console.log("preSunImg", t)
    var a = t.currentTarget.dataset.imageindex, e = t.currentTarget.dataset.imgdata || [];
    var c = [];
    for (var index in e) {
      c.push(e[index].imgUrl)
    }
    common_Js.preImg(a, c)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  // onPullDownRefresh: function () {
  //   this.refreshdeviceList()
  // },
  refreshdeviceList:function(){
    this.setData({
      loading: false,
      netWork: false,
      isLoading: true,
      deviceList:[]
    })
    this.data.pageIndex = 1;
    this.onHttpInit()
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      isLoading: true
    })
    this.onHttpInit()
  },
  goHandle:function(res){
    console.log('goHandle res',res)
    var id = res.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/terminal/handle/index?id='+id,
    })
  },
  goPowerRecord(e){
    var deviceId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/device/record/power/index?id='+deviceId,
    })
  },
  goChangeData(e){
    var deviceId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/device/changData/index?id='+deviceId,
    })
  },
  goChart:function(res){
    var id = res.currentTarget.dataset.id;
    var num = res.currentTarget.dataset.num;
    var nodecount = res.currentTarget.dataset.nodecount;
    var linkParam = "qrtype=device&num=" +num+"&id="+id+"&node_count="+nodecount;
    wx.navigateTo({ url: '/pages/device/chart/test?' + linkParam })
  },
  goRangeChart(res){
    var id = res.currentTarget.dataset.id;
    var num = res.currentTarget.dataset.num;
    var linkParam = "qrtype=range&num=" +num+"&id="+id;
    wx.navigateTo({ url: '/pages/device/range/chart/index?' + linkParam })
  },
  goRangeResult(res){
    var id = res.currentTarget.dataset.id;
    var num = res.currentTarget.dataset.num;
    var linkParam = "qrtype=result&num=" +num+"&id="+id;
    wx.navigateTo({ url: '/pages/device/range/result/index?' + linkParam })
  },
  goRecord(res){
    var id = res.currentTarget.dataset.id;
    var num = res.currentTarget.dataset.num;
    var linkParam = "qrtype=device&num=" +num+"&id="+id;
    wx.navigateTo({ url: '/pages/device/record/index?' + linkParam })
  },
  bindFeedChange(res){
    console.log('11111111111111111111', res)
    var that = this
    let node = res.currentTarget.dataset.current
    let value = res.detail.value
    let feed = that.data.feedList[Number(value)]
    fetchApi.httpPost('/device/editNodeFeed', {
      feed_id: feed.id,
      feed_name: feed.feedName,
      node_id: node.id
    }, function (res) {
      if (res.data.code == 0) {
        Toast("保存成功");
        that.refreshdeviceList()
      }else{
        Toast("保存失败");
      }
    })
  },
  onFeedSwichClose() {
    this.setData({
      feedSwitch: false
    })
  },
  //点击确定搜索时触发事件
  onSearch() {
    let row = [];
    if (this.data.searchKey.length > 0) {
      this.data.feedList.filter(
        (e) => {
          if (e.feedName.indexOf(this.data.searchKey.toLowerCase()) != -1) {
            row.push(e)
          }
        })
    } else {
      row = this.data.feedList
    }
    this.setData({
      // cognizance: this.data.searchKey,
      copyFeedList: row
    })
  },
  openSwitch(event) {
    let node = event.currentTarget.dataset.current
    this.selectNode = node
    this.setData({
      feedSwitch: true,
      searchKey: '',
      copyFeedList: this.data.feedList
    })
  },
  resetColumns() {
    this.setData({
      searchKey: '',
      copyFeedList: this.data.feedList
    })
  },
  feedShutdown() {
    this.setData({
      feedSwitch: false,
      searchKey: '',
    })
    this.resetColumns()
  },
  feedIdentification(event) {
    let that = this
    let feed = event.detail.value
    let index = event.detail.index
    let node = that.selectNode
    fetchApi.httpPost('/device/editNodeFeed', {
      feed_id: feed.id,
      feed_name: feed.feedName,
      node_id: node.id
    }, function (res) {
      if (res.data.code == 0) {
        that.onFeedSwichClose();
        Toast("保存成功");
        that.refreshdeviceList()
      }else{
        that.onFeedSwichClose();
        Toast("保存失败");

      }
    })
  },
})